import ejs from 'ejs';
import { renderToString } from 'react-dom/server';
import { Helmet } from 'react-helmet';

/**
 * 生成模板
 * @param {*} bundle webpack 打包的bundle
 */
const renderString = (bundle,template,initState={}) => {
  const appString = renderToString(bundle);
  const helmet = Helmet.renderStatic();
  const html = ejs.render(template, {
    meta: helmet.meta.toString(),
    link: helmet.link.toString(),
    style: helmet.style.toString(),
    title: helmet.title.toString(),
    appString,
    initalState: JSON.stringify(initState),
  })
  return html;
};

/**
 * 生成内容
 */
const renderStream = (jspath) => {

  const headerContent = `
    <!DOCTYPE html>
      <html>
      <head>
        <meta charSet='utf-8'>
        <meta httpEquiv='X-UA-Compatible' content='IE=edge'>
        <meta httpEquiv='Cache-Control' content='no-siteapp'>
        <meta name='renderer' content='webkit'>
        <meta name='viewport' content='width=device-width, initial-scale=1'>
      </head>

      <body>
  `;
  const wrapperContent = '<div id="root">';
  const footContent = `
    </div>
      <script type="text/javascript" src=${jspath}></script>
    </body>
    </html>
  `;
  return {
    headerContent,
    wrapperContent,
    footContent
  };
};

export default {
  renderString,
  renderStream
};
